import type { User, LoginForm, RegisterForm } from '@/types'

export class AuthService {
  private static readonly USERS_KEY = 'users'
  private static readonly CURRENT_USER_KEY = 'currentUser'

  /**
   * 获取所有用户
   */
  static getUsers(): User[] {
    const usersJson = localStorage.getItem(this.USERS_KEY)
    if (!usersJson) {
      // 如果没有用户数据，创建默认测试用户
      const defaultUsers = this.createDefaultUsers()
      this.saveUsers(defaultUsers)
      return defaultUsers
    }
    try {
      return JSON.parse(usersJson)
    } catch (error) {
      console.error('解析用户数据失败:', error)
      return []
    }
  }

  /**
   * 创建默认测试用户
   */
  private static createDefaultUsers(): User[] {
    return [
      {
        id: 'teacher-001',
        name: '测试教师',
        email: 'teacher@test.com',
        password: '123456',
        role: 'teacher',
        teacherId: 'T001',
        subject: ['数学', '物理'],
        classes: ['高一1班', '高一2班'],
        avatar: '',
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      },
      {
        id: 'student-001',
        name: '测试学生',
        email: 'student@test.com',
        password: '123456',
        role: 'student',
        studentId: 'S001',
        class: '高一1班',
        grade: '高一',
        avatar: '',
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      }
    ]
  }

  /**
   * 保存用户到localStorage
   */
  static saveUsers(users: User[]): void {
    try {
      localStorage.setItem(this.USERS_KEY, JSON.stringify(users))
    } catch (error) {
      console.error('保存用户数据失败:', error)
      throw new Error('保存用户数据失败')
    }
  }

  /**
   * 用户注册
   */
  static register(registerForm: RegisterForm): { success: boolean; message: string; user?: User } {
    try {
      const users = this.getUsers()
      
      // 检查邮箱是否已存在
      const existingUser = users.find(user => user.email === registerForm.email)
      if (existingUser) {
        return { success: false, message: '该邮箱已被注册' }
      }

      // 检查密码确认
      if (registerForm.password !== registerForm.confirmPassword) {
        return { success: false, message: '两次输入的密码不一致' }
      }

      // 创建新用户
      const newUser: User = {
        id: this.generateId(),
        name: registerForm.name,
        email: registerForm.email,
        password: registerForm.password, // 实际项目中应该加密
        role: registerForm.role,
        createdAt: new Date(),
        updatedAt: new Date()
      }

      // 根据角色添加特定字段
      if (registerForm.role === 'teacher') {
        newUser.teacherId = registerForm.teacherId || this.generateTeacherId()
        newUser.subject = registerForm.subject || []
        newUser.classes = registerForm.classes || []
      } else {
        newUser.studentId = registerForm.studentId || this.generateStudentId()
        newUser.class = registerForm.class || ''
        newUser.grade = registerForm.grade || ''
      }

      // 保存用户
      users.push(newUser)
      this.saveUsers(users)

      return { success: true, message: '注册成功', user: newUser }
    } catch (error) {
      console.error('注册失败:', error)
      return { success: false, message: '注册失败，请重试' }
    }
  }

  /**
   * 用户登录
   */
  static login(loginForm: LoginForm): { success: boolean; message: string; user?: User } {
    try {
      const users = this.getUsers()
      
      // 查找用户
      const user = users.find(u => 
        u.email === loginForm.email && 
        u.password === loginForm.password && 
        u.role === loginForm.role
      )

      if (!user) {
        return { success: false, message: '邮箱、密码或身份选择错误' }
      }

      // 保存当前用户信息
      this.setCurrentUser(user)

      return { success: true, message: '登录成功', user }
    } catch (error) {
      console.error('登录失败:', error)
      return { success: false, message: '登录失败，请重试' }
    }
  }

  /**
   * 用户登出
   */
  static logout(): void {
    try {
      localStorage.removeItem(this.CURRENT_USER_KEY)
    } catch (error) {
      console.error('登出失败:', error)
    }
  }

  /**
   * 获取当前用户
   */
  static getCurrentUser(): User | null {
    try {
      const userJson = localStorage.getItem(this.CURRENT_USER_KEY)
      if (!userJson) {
        return null
      }
      return JSON.parse(userJson)
    } catch (error) {
      console.error('获取当前用户失败:', error)
      return null
    }
  }

  /**
   * 设置当前用户
   */
  static setCurrentUser(user: User): void {
    try {
      localStorage.setItem(this.CURRENT_USER_KEY, JSON.stringify(user))
    } catch (error) {
      console.error('设置当前用户失败:', error)
    }
  }

  /**
   * 检查是否已登录
   */
  static isAuthenticated(): boolean {
    return this.getCurrentUser() !== null
  }

  /**
   * 检查用户角色
   */
  static hasRole(role: 'teacher' | 'student'): boolean {
    const user = this.getCurrentUser()
    return user?.role === role
  }

  /**
   * 生成唯一ID
   */
  private static generateId(): string {
    return Date.now().toString(36) + Math.random().toString(36).substr(2)
  }

  /**
   * 生成教师ID
   */
  private static generateTeacherId(): string {
    return 'T' + Date.now().toString().slice(-8)
  }

  /**
   * 生成学生ID
   */
  private static generateStudentId(): string {
    return 'S' + Date.now().toString().slice(-8)
  }

  /**
   * 验证邮箱格式
   */
  static validateEmail(email: string): boolean {
    const emailRegex = /^[a-zA-Z][a-zA-Z0-9._-]*@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
    return emailRegex.test(email)
  }

  /**
   * 验证密码强度
   */
  static validatePassword(password: string): { valid: boolean; message: string } {
    if (password.length < 6) {
      return { valid: false, message: '密码长度至少6位' }
    }
    if (!/(?=.*[a-zA-Z])(?=.*\d)/.test(password)) {
      return { valid: false, message: '密码必须包含字母和数字' }
    }
    return { valid: true, message: '密码强度合格' }
  }
}